package com.concurrent.coline.part13;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class ThreadMethodDemo {
    private static class MyWork implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class MyCallable implements Callable {

        @Override
        public String call() throws Exception {
            return "Callable: " + Thread.currentThread().getName();
        }
    }

    public static void main(String[] arg0) throws ExecutionException, InterruptedException {
        ThreadFactory demoThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-thread-%d").build();
        ExecutorService threadPool = new ThreadPoolExecutor(2, 4
                , 10L, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(10), demoThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 10; i++) {
            MyWork work = new MyWork();
            threadPool.execute(work);
        }

        for (int i = 0; i < 10; i++) {
            MyCallable myCallable = new MyCallable();
            Future result = threadPool.submit(myCallable);
            System.out.println(result.get());
        }

        threadPool.shutdown();


    }

}
